<template>
  <div class="container">
    <h2>新增收货地址</h2>
    <!-- 地址表单 -->
    <el-form :model="addressForm" :rules="rules" ref="addressFormRef" label-width="100px">
      <el-form-item label="姓名" prop="name">
        <el-input v-model="addressForm.name" placeholder="请输入姓名" maxlength="10"></el-input>
      </el-form-item>
      <el-form-item label="电话号" prop="phone">
        <el-input
            v-model="addressForm.phone"
            maxlength="11"
            minlength="11"
            placeholder="请输入11位电话号码"
            show-word-limit
        ></el-input>
      </el-form-item>
      <el-form-item label="详细地址" prop="address">
        <el-select v-model="addressForm.address" placeholder="请选择详细地址">
          <el-option label="1 公寓" value="1 公寓"></el-option>
          <el-option label="2 公寓" value="2 公寓"></el-option>
          <el-option label="6 公寓" value="6 公寓"></el-option>
        </el-select>
      </el-form-item>
      <div class="button-container">
        <!-- 返回按钮 -->
        <router-link to="/home/canteen/address" tag="el-button" type="primary" class="return-button">
          返回
        </router-link>
        <!-- 提交按钮 -->
        <el-button type="primary" class="submit-button" @click="handleSubmit">提交</el-button>
      </div>
    </el-form>
  </div>
</template>

<script>
import { reactive, ref } from 'vue';
import request from '@/utils/canteen';
import { ElMessage } from 'element-plus';
import { useRouter } from 'vue-router';

export default {
  name: "AddressDetail",
  setup() {
    const router = useRouter();
    const addressForm = reactive({
      stuid: 0, // 初始化stuid属性
      name: '',
      phone: '',
      address: ''
    });

    const addressFormRef = ref(null); // 创建一个ref引用form

    // 从sessionStorage获取当前登录学生的loginUser对象
    const loginUserFromStorage = sessionStorage.getItem('loginUser');
    if (loginUserFromStorage) {
      const loginUser = JSON.parse(loginUserFromStorage);
      addressForm.stuid = loginUser.id; // 设置stuid
    }

    // 验证规则
    const rules = reactive({
      name: [
        { required: true, message: '请输入姓名', trigger: 'blur' },
        { min: 2, max: 10, message: '长度在 2 到 10 个字符', trigger: 'blur' }
      ],
      phone: [
        { required: true, message: '必须填写手机号', trigger: 'blur' },
        {
          pattern: /^(?:13[3-9]|14[5-9]|15[0-3]|15[5-9]|16[6]|17[3]|18[2-9]|19[3-9])[0-9]{8}$/,
          message: '格式不正确，请输入有效的手机号',
          trigger: 'blur'
        }
      ],
      address: [
        { required: true, message: '请选择地址', trigger: 'blur' }
      ]
    });

    const handleSubmit = () => {
      addressFormRef.value.validate((valid) => {
        if (valid) {
          request({
            url: '/address/add',
            method: 'post',
            data: addressForm
          }).then((response) => {
            if (response.status === 200) {
              ElMessage.success('地址添加成功');
              router.push('/home/canteen/address'); // 添加成功后返回地址列表页面
            } else {
              ElMessage.error('地址添加失败');
            }
          }).catch((error) => {
            ElMessage.error('添加地址时发生错误');
            console.error(error);
          });
        } else {
          // 如果验证失败，则显示错误信息
          ElMessage.error('表单验证失败');
          return false;
        }
      });
    };

    return {
      addressForm,
      rules,
      handleSubmit,
      addressFormRef // 需要返回以便在模板中使用
    };
  }
};
</script>

<style scoped>
/* 页面容器样式 */
.container {
  max-width: 500px;
  margin: 0 auto;
  padding: 20px;
  background: #fff;
  box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
  border-radius: 8px;
  margin-top: 70px;
}

/* 标题样式 */
h2 {
  color: #333;
  font-size: 24px;
  text-align: center;
  margin-bottom: 20px;
}

/* 按钮容器样式 */
.button-container {
  display: flex;           /* 使用Flexbox布局 */
  justify-content: space-between; /* 按钮间隔分布 */
  margin-bottom: 20px;     /* 根据需要调整外边距 */
}

/* 返回按钮样式调整 */
.return-button {
  margin: 0;                /* 移除原有外边距 */
  width: auto;              /* 按钮宽度自适应 */
  padding: 10px 20px;       /* 调整内边距 */
}

/* 提交按钮样式调整 */
.submit-button {
  margin: 0;                /* 移除原有外边距 */
  width: auto;              /* 按钮宽度自适应 */
}
/* 表单样式 */
.el-form {
  width: 100%;
}

/* 表单标题样式 */
.el-form-item__label {
  font-weight: 500;
  color: #666;
}

/* 输入框和选择框样式 */
.el-form-item__content {
  margin-left: 0 !important;
}

.el-input__inner, .el-select .el-input__inner {
  width: 100%; /* 调整输入框宽度为100% */
  border-radius: 4px;
  border-color: #dcdfe6;
  transition: border-color 0.2s;
  padding: 0 10px;
  height: 36px;
}

.el-input__inner:focus, .el-select .el-input__inner:focus {
  border-color: #409eff;
}

/* 按钮样式 */
.el-button {
  border-radius: 20px;
  padding: 10px 20px;
  font-size: 16px;
  transition: background-color 0.2s, box-shadow 0.2s;
}

.el-button--primary {
  background-color: #409eff;
  border-color: #409eff;
}

.el-button--primary:hover {
  background-color: #66b1ff;
  border-color: #66b1ff;
  box-shadow: 0 0 10px rgba(64, 158, 255, 0.5);
}


/* 模态框和消息提示的样式可以根据Element Plus的文档进行定制 */
</style>